import { ref, onMounted, onUnmounted } from 'vue'

export function useDeviceDetect(mobileBreakpoint = 768) {
  // 响应式状态
  const isMobile = ref(false)
  const isTablet = ref(false)
  const isPortrait = ref(true)
  const deviceInfo = ref({
    width: 0,
    height: 0,
    pixelRatio: 1,
    userAgent: '',
    platform: '',
    isTouch: false
  })

  // 检测是否为移动设备的 UA 关键词
  const MOBILE_UA_KEYWORDS = [
    'mobile',
    'android',
    'iphone',
    'ipod',
    'webos',
    'opera mini'
  ]

  // 检测是否为平板设备的 UA 关键词
  const TABLET_UA_KEYWORDS = [
    'ipad',
    'tablet',
    'kindle',
    'playbook',
    'silk'
  ]

  // 更新设备信息
  const updateDeviceInfo = () => {
    const ua = navigator.userAgent.toLowerCase()
    const platform = navigator.platform
    const width = window.innerWidth || document.documentElement.clientWidth
    const height = window.innerHeight || document.documentElement.clientHeight

    // 更新设备基本信息
    deviceInfo.value = {
      width,
      height,
      pixelRatio: window.devicePixelRatio || 1,
      userAgent: ua,
      platform,
      isTouch: 'ontouchstart' in window || navigator.maxTouchPoints > 0
    }

    // 检测设备类型
    const isMobileUA = MOBILE_UA_KEYWORDS.some(keyword => ua.includes(keyword))
    const isTabletUA = TABLET_UA_KEYWORDS.some(keyword => ua.includes(keyword))
    
    // 更新屏幕方向
    isPortrait.value = height > width

    // 综合判断设备类型
    // 1. 首先通过屏幕宽度判断
    // 2. 然后结合 UA 和触摸支持进行判断
    // 3. 最后考虑特殊情况（如 iPad）
    if (width <= mobileBreakpoint) {
      isMobile.value = true
      isTablet.value = false
    } else if (width <= 1024) {
      isMobile.value = false
      isTablet.value = true
    } else {
      // 宽屏设备，但仍需检查是否为移动设备
      isMobile.value = isMobileUA && deviceInfo.value.isTouch
      isTablet.value = isTabletUA && deviceInfo.value.isTouch
    }

    // iPad 特殊处理
    if (ua.includes('ipad') || (ua.includes('macintosh') && deviceInfo.value.isTouch)) {
      isMobile.value = false
      isTablet.value = true
    }

    // 调试信息
    if (process.env.NODE_ENV === 'development') {
      console.log('Device Detection:', {
        width,
        height,
        pixelRatio: deviceInfo.value.pixelRatio,
        isTouch: deviceInfo.value.isTouch,
        isMobileUA,
        isTabletUA,
        isPortrait: isPortrait.value,
        isMobile: isMobile.value,
        isTablet: isTablet.value,
        userAgent: ua
      })
    }
  }

  // 设置移动端视口
  const setupViewport = () => {
    let viewportContent = 'width=device-width, initial-scale=1'
    
    // 如果是移动设备，添加额外的视口设置
    if (isMobile.value || isTablet.value) {
      viewportContent += ', maximum-scale=1, user-scalable=no'
    }

    const viewport = document.querySelector('meta[name="viewport"]')
    if (!viewport) {
      const meta = document.createElement('meta')
      meta.name = 'viewport'
      meta.content = viewportContent
      document.head.appendChild(meta)
    } else {
      viewport.setAttribute('content', viewportContent)
    }
  }

  // 防抖处理
  let resizeTimer: number | null = null
  const handleResize = () => {
    if (resizeTimer) {
      window.clearTimeout(resizeTimer)
    }
    resizeTimer = window.setTimeout(() => {
      updateDeviceInfo()
      setupViewport()
    }, 100)
  }

  // 处理屏幕方向变化
  const handleOrientationChange = () => {
    // 延迟处理，等待方向变化完成
    setTimeout(() => {
      updateDeviceInfo()
      setupViewport()
    }, 100)
  }

  // 组件挂载时初始化
  onMounted(() => {
    updateDeviceInfo()
    setupViewport()
    
    // 添加事件监听
    window.addEventListener('resize', handleResize, false)
    window.addEventListener('orientationchange', handleOrientationChange, false)
  })

  // 组件卸载时清理
  onUnmounted(() => {
    if (resizeTimer) {
      window.clearTimeout(resizeTimer)
    }
    window.removeEventListener('resize', handleResize)
    window.removeEventListener('orientationchange', handleOrientationChange)
  })

  return {
    isMobile,
    isTablet,
    isPortrait,
    deviceInfo,
    updateDeviceInfo,
    setupViewport
  }
} 